import Vue from "vue";
import Router from "vue-router";
import routes from "./routes";
import NProgress from 'nprogress' // 进度条
import 'nprogress/nprogress.css'
import {Message} from "element-ui";

import {get_token} from '@/utils/token'
import {get_info, set_info} from '@/utils/info'
import {usr_info} from '@/api/auth'

Vue.use(Router);

const route = new Router({
    mode: 'history',
    routes
});

/**
 * 白名单
 */
const whiteList = ['/index', '/ticket', '/sysUser', '/login', '/register', '/hotelDetail'];


/**
 * 前置钩子 （全局导航守卫）
 */
route.beforeEach((to, from, next) => {
    if (to.meta.title) {
        document.title = to.meta.title
    }
    NProgress.start();
    let token = get_token();
    if (token) {
        if (to.path === '/index' || to.path === '/') {
            next({path: '/home'});
            NProgress.done()
        } else {
            let info = get_info();
            if (!info) {
                usr_info().then(res => {
                    if (res.status === '200') {
                        set_info(res.data);
                        console.log("---" + get_info())
                        next();
                        NProgress.done()
                    } else {
                        Message.error(res.data.msg);
                    }
                })
            } else {
                next();
                NProgress.done()
            }
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            next();
            NProgress.done()
        } else {
            // 否则全部重定向到登录页
            next(`/index`)
            NProgress.done()
        }
    }

});

/**
 * 后置钩子
 */
route.afterEach(() => {
    // 结束Progress
    NProgress.done()
});


export default route;
